<?php
namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Config;
use App\Http\model\Curdpost;
/**
* 定单控制器
*/
class OrderController extends Controller
{
	/**
	 * 主页-出收车状态1323
	 */
	public function carStatus(Request $requset)
	{
		$uid = $requset->get('id'); //司机id
		//司机当前状态
		$driverS = Db :: table('driver')->where('id',$uid)->select('attendant','is_zx')->first();
		$attendant = $this->driverStatus($driverS -> attendant);
		$returnArr['data']['attendant'] = $attendant;
		$returnArr['data']['is_zx'] = $driverS -> is_zx;
		//今日订单数量
		$begintime=strtotime(date("Y-m-d H:i:s",mktime(0,0,0,date('m'),date('d'),date('Y'))));
		$endtime=strtotime(date("Y-m-d H:i:s",mktime(0,0,0,date('m'),date('d')+1,date('Y'))-1));
		$countOrder = Db :: table('order')
						->leftJoin('order_extend','order.extendid','=','order_extend.id')
						->where('order_extend.driver_id',$uid)
						->whereBetween('order.usetime',[$begintime,$endtime])
						->count();
		$returnArr['data']['countOrder'] = (string)$countOrder;
		//营运里程
		$sumdis = Db :: table('order')
					->leftJoin('order_extend','order.extendid','=','order_extend.id')
					->leftJoin('order_long','order.id','=','order_long.oid')
					->where('order_extend.driver_id',$uid)
					->where('order.orderstatus',4)
					->sum('endlong');
		$returnArr['data']['sumdis'] = (string)$sumdis;
		//显示最近的第一个待完成订单
		$waitOrder = Db :: table('order')
						->leftJoin('order_extend','order.extendid','=','order_extend.id')
						->leftJoin('server_item','order.typeid','=','server_item.id')
						->where('order_extend.driver_id',$uid)
						->where('order.orderstatus',1)
						->orderBy('order.id','desc')
						->select('order.usetime','server_item.name')
						->first();
		$waitOrder = json_decode(json_encode($waitOrder),true);
		$waitOrderStr = date('Y-m-d H:i:s',$waitOrder['usetime']).'您有'.$waitOrder['name'].'订单要完成，请提前备车';
		if(!empty($waitOrder)){
			$returnArr['data']['waitOrder'] = $waitOrderStr;
		}else{
			$returnArr['data']['waitOrder'] = '';
		}
		
		//显示已接单到服务结束的订单
		$statusArr = [3,4,5,6,7,8];
		$serOrder = Db :: table('order')
						->leftJoin('order_extend','order.extendid','=','order_extend.id')
						->where('order_extend.driver_id',$uid)
						->whereIn('order.implementstatus',$statusArr)
						->select('order.implementstatus','order.original','order.end','order.id','order.usetime')
						->get();
		$serOrder = json_decode(json_encode($serOrder),true);
		foreach ($serOrder as $key => &$value) {
			$value['statusFlag'] = $value['implementstatus'];
			$value['implementstatus'] = $this->orderStatus($value['implementstatus']);
			$value['usetime'] = date('Y-m-d H:i:s',$value['usetime']);
		}
		$returnArr['data']['orderList'] = $serOrder;
		//待接单数量
		 $countWait = Db :: table('order')
					    ->leftJoin('order_extend','order.extendid','=','order_extend.id')
						->where('order_extend.driver_id',$uid)
						->where('order.implementstatus',2)
						->count();
		$returnArr['data']['countWait'] = (string)$countWait;
		$returnArr['code'] = '1000';
		$returnArr['msg'] = '请求成功';
		echo json_encode($returnArr);

	}
	/**
	 * 服务订单列表页
	 * types 未接单1    所有订单2
	 */
	public function serOrderList(Request $requset)
	{
		$uid = $requset->get('id'); //司机id
		$types = $requset['types'];
		if($types == 1){
			$statusArr = [2];
		}elseif ($types == 2) {
			$statusArr = [2,3,4,5,6,7,8,9];
		}
		$serOrder = Db :: table('order')
						->leftJoin('order_extend','order.extendid','=','order_extend.id')
						->leftJoin('server_item','order.typeid','=','server_item.id')
						->where('order_extend.driver_id',$uid)
						->whereIn('order.implementstatus',$statusArr)
						->select('order.id','order.implementstatus','order.original','order.end','order.usetime','server_item.name','order_extend.cip_num')
						->get();
		$serOrder = json_decode(json_encode($serOrder),true);
		foreach ($serOrder as $key => &$value) {
			$value['implementstatus'] = $this->orderStatus($value['implementstatus']);
			if($value['cip_num'] > 0){
				$value['iscip'] = 2;
			}else{
				$value['iscip'] = 1;
			}
		}
		$returnArr['data'] = $serOrder;
		$returnArr['code'] = '1000';
		$returnArr['msg'] = '请求成功';
		echo json_encode($returnArr);

	}
	/**
	 * 订单详情页
	 * @return [type] [description]
	 */
	public function orderDetail(Request $requset)
	{
		$oid = $requset['oid'];//订单id
		$detail = Db :: table('order')
				->leftJoin('order_extend','order.extendid','=','order_extend.id')
				->leftJoin('order_long','order.id','=','order_long.oid')
				->leftJoin('server_item','order.typeid','=','server_item.id')
				->leftJoin('social_user','order.uid','=','social_user.id')
				->where('order.id',$oid)
				->select('order.id','order.original','order.end','order.originaldegree','order.enddegree','order.usetime','order_extend.passenger_name','order_extend.passenger_phone','order_extend.fightnum','server_item.name','order_long.prelong','order_long.pretime','social_user.nickname','order.num','order.sumpeople','order.implementstatus')
				->first();
		$detail = json_decode(json_encode($detail),true);
		$originaldegree = explode(',',$detail['originaldegree']);
		$ori = $originaldegree[1].','.$originaldegree[0];
		$enddegree = explode(',',$detail['enddegree']);
		$des = $enddegree[1].','.$enddegree[0];
		$detailDis = $this->countdis($ori,$des);
		if($detailDis['code'] == '200'){
			$detail['distance'] = $detailDis['data'][0]['distance'];
			$detail['time'] = $detailDis['data'][0]['time'];
		}else{
			$detail['distance'] = '0';
			$detail['time'] = '0';
		}
		$detail['usetime'] = (string)$detail['usetime'];
		$returnArr['data']['top'] = $detail;
		$arr = [
			[
				"title"=> "订单编号",
                "content"=>$detail['num']
			],
			[
				"title"=> "下单人",
                "content"=>$detail['nickname']
			],
			[
				"title"=> "服务类型",
                "content"=>$detail['name']
			],
			[
				"title"=> "用车时间",
                "content"=>date('Y-m-d H:i:s',$detail['usetime'])
			],
			[
				"title"=> "乘车人",
                "content"=>$detail['passenger_name']
			],
			[
				"title"=> "联系电话",
                "content"=>$detail['passenger_phone']
			],
			[
				"title"=> "上车地",
                "content"=>$detail['original']
			],
			[
				"title"=> "下车地",
                "content"=>$detail['end']
			],
		];
		$returnArr['data']['detail'] = $arr;
		$returnArr['data']['du']['originaldegree'] = $detail['originaldegree'];
		$returnArr['data']['du']['enddegree'] = $detail['enddegree'];
		$returnArr['code'] = '1000';
		$returnArr['msg'] = '请求成功';
		echo json_encode($returnArr);
	}
	/**
	 * 修改订单状态
	 * 3司机接单，4备车，5前往预约地点，6到达指定地，	7开始服务，8即将到达，9结束服务
	 * @return [type] [description]
	 */
	public function changeOrderStatus(Request $requset)
	{
		$status = $requset['status'];
		$oid = $requset['id'];
		$order = Db :: table('order')
					->leftJoin('order_extend','order.extendid','=','order_extend.id')
					->leftJoin('driver','order_extend.driver_id','=','driver.id')
					->leftJoin('car_car','driver.car_id','=','car_car.id')
					->leftJoin('car_type','car_car.typeid','=','car_type.id')
					->where('order.id',$oid)
					->select('order.num','order.originaldegree','order.typeid','order.usetime','order.areacode','car_type.sid','order.uid','driver.licenseId','car_car.num as carnum','driver.driver_phone','car_car.mileage','order.enddegree')
					->first();
		$num = $order -> num;
		if($status == 3){
			$arr['orderstatus'] = 2;
		}elseif ($status == 9) {
			$arr['orderstatus'] = 4;
		}else{
			$arr['orderstatus'] = 3;
		}
		$arr['implementstatus'] = $status;
		$insertArr = [
			'order_number'=>$num,
			'status'=>$status,
			'update_time'=>time()
		];
		//更改数据库状态
		DB::beginTransaction();
		try {
			Db :: table('order')->where('id',$oid)->update($arr);
			Db :: table('order_status')->insert($insertArr);
			DB::commit();
		} catch (Exception $e) {
			DB::rollBack();
		}

		//返回距离信息
		if(!empty($requset['ori'])){
			$ori = $requset['ori'];//起点  经，纬
			$des = $order -> enddegree;//终点  经，纬
			$oriArr = explode(',', $ori);
			$desArr = explode(',',$des);
			$trueOri = $oriArr[1] . ',' .$oriArr[0];
			$trueDes = $desArr[1] . ',' .$desArr[0];
			$re = $this->countdis($trueOri,$trueDes);
			if($re['code'] == '200'){
				$arr['data']['distance'] = $re['data'][0]['distance'];
				$arr['data']['time'] = $re['data'][0]['time'];
			}else{
				$arr['data']['distance'] = 0;
				$arr['data']['time'] = 0;
			}
		}
		//结束服务的时候修改价格,提供结束地址经纬度
		if($requset['status'] == 9){
			$originaldegree = $order -> originaldegree;
			$oriA = explode(',',$originaldegree);
			$origins = $oriA[1] . ',' . $oriA[0];
			$desA = explode(',',$requset['ori']);
			$destinations = $desA[1] . ',' . $desA[0];
			$typeid = Db :: table('server_item')->where('id',$order -> typeid)->select('name')->first();
			$types = $typeid->name;
			$usetime = date('Y-m-d H:i',$order -> usetime);
			$areaid = $order -> areacode;
			$carid = $order -> sid;
			//dump($carid);
			//计算最终价格
			$newPrice = $this->price($origins, $destinations,$types, $usetime, $carid, $areaid);
		//	dump($newPrice);
			if($newPrice['price'] != 0){
				//更新订单距离表
				$long = [
					'endlong'=>$newPrice['dis'],
					'endtime'=>$newPrice['time']
				];
				Db :: table('order_long')->where('oid',$oid)->update($long);
				//计算差价
				$preprice = Db :: table('order_price')->where('oid',$oid)->select('preprice')->first();
				$pre = $preprice -> preprice;
				$difprice = $newPrice['price'] - $pre;
				if($difprice > 0){
					$difp = $difprice;
					$wystatus = 0;
				}elseif ($difprice == 0) {
					//订单状态更新为结算
					Db :: table('order')->where('id',$oid)->update(['jiesuanstatus'=>2]);
					$difp = $difprice;
					$wystatus = 1;
				}else{
					//给用户退钱
					Db :: table('social_user')->where('id',$order->uid)->increment('sum_money',$difprice);
					//订单状态更新为结算
					Db :: table('order')->where('id',$oid)->update(['jiesuanstatus'=>2]);
					$difp = 0;
					$wystatus = 1;
				}
				//拿目前收费规则
				$cost = Db :: table('cost')
								->where('sername',$order->typeid)->where('serid',$order->sid)
								->select('id','city')->get();
        		$cost = json_decode(json_encode($cost),true);	
        		$historyId = '';
        		foreach ($cost as $key => $value) {
		        	$valueArr = explode(',',$value['city']);
		        	if(in_array($areaid,$valueArr)){
		        		 $historyId = $value['id'];
		        		 continue;
		        	}
		        }
		        $algorithmid = Db :: table('history_algorithm')
       						->where('costid',$historyId)
       						->orderBy('id','desc')->select('algorithmid')->first();
       			$algorithmid = json_decode(json_encode($algorithmid),true);
       			$algorithmidStr = $algorithmid['algorithmid'];
       			$charge = Config::get('charge.'.$algorithmidStr);
				//等待费
				$difTime = Db :: table('order_status')
								->where('order_number',$order->num)
								->whereIn('status',[6,7])
								->select('update_time')
								->get();
				$difTime = json_decode(json_encode($difTime),true);
				if(count($difTime) == 2){
					//等待时间
					$difT = abs(($difTime[0]['update_time'] - $difTime[1]['update_time'])/60);
					
       				if($difT > $charge['over_time']){
       					$evDifT = $difT - $charge['over_time'];
       					if($evDifT > $charge['over_shortage_time']){
       						$waitprice = $evDifT * $charge['over_add_money'];
       					}else{
       						$waitprice = $charge['over_arrivals_add_money'];
       					}
       				}else{
       					$waitprice = $charge['over_arrivals_add_money'];
       				}
				}else{
					$waitprice = 0;
				}
				
				$endPrice = [
					'endprice'=>$newPrice['price'],
					'difprice'=>$difp,
					'waitprice'=>$waitprice,
					'runprice'=>$newPrice['runprice'],
					//'longprice'=>
					'oversprice'=>$newPrice['oversprice'] - $newPrice['runprice'],
					'overlprice'=>$newPrice['runprice'] - $charge['price']
				];
				//dump($endPrice );
				Db :: table('order_price')->where('oid',$oid)->update($endPrice);
				$DepTime = Db :: table('order_status')
								->where('order_number',$num)->where('status',7)->select('update_time')->first();
				
				$inteDb = new Curdpost();
				$operatepay = 'operatepay';
				$enddegree = $order -> enddegree;
				$end = explode(',',$enddegree);
				$operatepayArr = [
					'CompanyId'=>'test',
					'orderId'=>$num,
					'OnArea'=>$order -> areacode,
					'LicenseId'=>$order -> licenseId,
					'FareType'=>'test',
					'VehicleNo'=>$order -> carnum,
					'BookDepTime'=>date('YmdHis',$order->usetime),
					'DepLongitude'=>$oriA[0],
					'DepLatitude'=>$oriA[1],
					'DepTime'=>date('YmdHis',$DepTime->update_time),
					'DestLongitude'=>$end[0],
					'DestLatitude'=>$end[1],
					'DestTime'=>date('YmdHis',time()),
					'DriveMile'=>$re['data2'][0]['distance']/1000,
					'DriveTime'=>$re['data2'][0]['time'],
					'FactPrice'=>$newPrice['price'],
					'FarUpPrice'=>0,
					'OtherUpPrice'=>0,
					'PayState'=>$wystatus,
					'InvoiceStatus'=>2
				];
				$inteDb->NewInsert($operatepay,$operatepayArr);
			}
			

		}
		//更新网约车数据库   $requset['status']
		//3司机接单，4备车，5前往预约地点，6到达指定地，	7开始服务，8即将到达，9结束服务
		$inteDb = new Curdpost();
		if($requset['status'] == 5){//经营出发
			$ori = explode(',',$requset['ori']);
			$operatedepart = 'operatedepart';
			$operatedepartArr = [
				'CompanyId'=>'test',
				'OrderId'=>$num,
				'LicenseId'=>$order -> licenseId,
				'FareType'=>'test',
				'VehicleNo'=>$order -> carnum,
				'DepLongitude'=>$ori[0],
				'DepLatitude'=>$ori[1],
				'Encrypt'=>3,
				'DepTime'=>date('YmdHis',time()),
			];
			$inteDb->NewInsert($operatedepart,$operatedepartArr);
		}
		if($requset['status'] == 6){
			//更新空驶里程
			$originaldegree = $order -> originaldegree;
			$oriA = explode(',',$originaldegree);
			$origins = $oriA[1] . ',' . $oriA[0];
			$desA = explode(',',$requset['ori']);
			$destinations = $desA[1] . ',' . $desA[0];
			$conutdis = $this->countdis($origins,$destinations);
			$WaitMile = ['WaitMile'=>$conutdis['data'][0]['distance']];
			$operatedepart = 'operatedepart';
			$WaitMileWhere = 'OrderId = "'.$num.'"';
			$inteDb -> NewUpdate($operatedepart,$WaitMile,$WaitMileWhere);

		}
		if ($requset['status'] == 7) {
			$update_time = Db :: table('order_status')
								->where('order_number',$num)->where('status',6)->select('update_time')->first();
			$update_time = json_decode(json_encode($update_time),true);
			$WaitTime = ['WaitTime'=>time() - $update_time['update_time']];
			$operatedepart = 'operatedepart';
			$WaitMileWhere = 'OrderId = "'.$num.'"';
			$inteDb -> NewUpdate($operatedepart,$WaitTime,$WaitMileWhere);
		}
		if ($requset['status'] == 9) {
			//经营到达
			$operatearrive = 'operatearrive';
			//根据经纬度拿取时间距离
			$originaldegree = $order -> originaldegree;
			$oriA = explode(',',$originaldegree);
			$origins = $oriA[1] . ',' . $oriA[0];
			$desA = explode(',',$requset['ori']);
			$destinations = $desA[1] . ',' . $desA[0];
			$conutdis = $this->countdis($origins,$destinations);
			//表所需字段
			$operatearriveArr = [
				'CompanyId'=>'test',
				'OrderId'=>$num,
				'DestLongitude'=>$desA[0],
				'DestLatitude'=>$desA[1],
				'Encrypt'=>3,
				'DestTime'=>date('YmdHis',time()),
				'DriveMile'=>$conutdis['data2'][0]['distance'],
				'DriveTime'=>$conutdis['data2'][0]['time']
			];
			$inteDb->NewInsert($operatearrive,$operatearriveArr);
			//网约车驾驶员统计信息--完成订单次数
			
			//订单成功表
			$DistributeTime = Db :: table('order_status')
								  ->where('order_number',$num)->where('status',2)->select('update_time')->first();
			$DistributeTime = json_decode(json_encode($DistributeTime),true);
			$ordermatch = 'ordermatch';
			$ordermatchArr = [
				'CompanyId'=>'test',
				'Address'=>$order -> areacode,
				'OrderId'=>$num,
				'Longitude'=>$desA[0],
				'Latitude'=>$desA[1],
				'Encrypt'=>3,
				'LicenseId'=>$order -> licenseId,
				'DriverPhone'=>$order -> driver_phone,
				'VehicleNo'=>$order -> carnum,
				'DistributeTime'=>date('YmdHis',$DistributeTime['update_time'])
			];
			$inteDb->NewInsert($ordermatch,$ordermatchArr);
		}
		//驾驶员定位信息
		$licenseId = $order -> licenseId;
		$positiondriver = 'positiondriver';
		$positiondriverWhere = 'LicenseId = "'.$licenseId.'"';
		$re = $inteDb -> selectArr($positiondriver,$positiondriverWhere);
		$desA = explode(',',$requset['ori']);
		//拿取高度，速度，方向
		$position = $this->getlatestpoint($order -> driver_phone);
		if($position['code'] == '200'){
			$Direction = $position['data']['direction'];
			$Elevation = $position['data']['height'];
			$Speed = $position['data']['speed'];
		}else{
			$Direction = '';
			$Elevation = '';
			$Speed = '';
		}
		//3司机接单，4备车，5前往预约地点，6到达指定地，	7开始服务，8即将到达，9结束服务
		////1：载客 2：接单 3：空驶 4:停运
		if($requset['status'] == 7 || $requset['status'] == 8){
			$BizStatus = 1;
		}elseif ($requset['status'] == 3) {
			$BizStatus = 2;
		}elseif ($requset['status'] == 9) {
			$BizStatus = 4;
		}else{
			$BizStatus = 3;
		}
		if($re['code'] == '1000'){
			$positiondriverCont = [
				'DriverRegionCode'=>$order -> areacode,
				'PositionTime'=>time(),
				'Longitude'=>$desA[0],
				'Latitude'=>$desA[1],
				'Enerypt'=>3,
				'Direction'=>$Direction,
				'Elevation'=>$Elevation,
				'Speed'=>$Speed,
				'OrderId'=>$num,
				'BizStatus'=>$BizStatus
			];
			$inteDb -> NewUpdate($positiondriver,$positiondriverCont,$positiondriverWhere);
		}
		//汽车定位信息
		$carnum = $order -> carnum;
		$positionvehicle = 'positionvehicle';
		$positionvehicleWhere = 'VehicleNo = "'.$carnum.'"';
		$re2 = $inteDb -> selectArr($positionvehicle,$positionvehicleWhere);
		if($re2['code'] == '1000'){
			$positionvehicleCont = [
				'VehicleRegionCode'=>$order -> areacode,
				'PositionTime'=>time(),
				'Longitude'=>$desA[0],
				'Latitude'=>$desA[1],
				'Speed'=>$Speed,
				'Direction'=>$Direction,
				'Elevation'=>$Elevation,
				'Mileage'=>$order->mileage,
				'BizStatus'=>$BizStatus,
				'OrderId'=>$num
			];
			$inteDb -> NewUpdate($positionvehicle,$positionvehicleCont,$positionvehicleWhere);
		}
		$arr['code'] = '1000';
		$arr['msg'] = '请求成功';
		echo json_encode($arr);

	}
	/**
	 * 司机对该订单的描述
	 */
	public function driverDescription(Request $request)
	{
		$oid = $request['oid'];//订单id
		$description = $requset['description'];//描述
		$extendid = Db :: table('order')->where('id',$oid)->select('extendid')->first();
		$eid = $extendid -> extendid;
		Db :: table('order_extend') -> where('id',$eid)->update(['driver_description'=>$description]);
		$arr['code'] = '1000';
		$arr['msg'] = '请求成功';
		echo json_encode($arr);
	}
		/*
		$ori  起点
		$des 终点
		计算两点之间的距离
	*/
	private function countdis($ori,$des)
	{
		//$ori = '39.916566441207,116.47672599552|40.047452206531,116.44685440027';
		//$des = '40.086792,116.594566';
		$url = 'http://api.map.baidu.com/routematrix/v2/driving?output=json&origins=' . $ori . '&destinations=' . $des . '&ak=RGwhFRkSZfva32BN96csoObm4FIfiCAY';
		$re = $this->get_curl_json($url);
		if($re['status'] == 0){
			$arr['code'] = '200';
			$arr['msg'] = '请求成功';
			$i = 0;
			foreach ($re['result'] as $key => $value) {
				$arr['data'][$i]['distance'] = $value['distance']['text'];
				$arr['data'][$i]['time'] = $value['duration']['text'];
				$arr['data2'][$i]['distance'] = $value['distance']['value'];
				$arr['data2'][$i]['time'] = $value['duration']['value'];
				$i++;
			}
		}else{
			$arr['code'] = '500';
			$arr['msg'] = '百度服务器错误';
			$arr['data'] = '';
		}
		return $arr;
	}
	/**
	 * 持续追踪某一终端，实时展示最新的纠偏后轨迹点，实时判断车辆所在道路的等级以及是否超速
	 */
	public function getlatestpoint($value)
	{
		$ak = 'RGwhFRkSZfva32BN96csoObm4FIfiCAY';
		$serid = 158008;
		$url = 'http://yingyan.baidu.com/api/v3/track/getlatestpoint?ak='.$ak.'&service_id='.$serid.'&entity_name='.$value;
		$re = $this->get_curl_json($url);
		$arr = [];
		if($re['status'] == 0){
			if(!empty($re['latest_point']['direction'])){
				$arr['data']['direction'] = $re['latest_point']['direction'];
			}else{
				$arr['data']['direction'] = '';
			}
			if (!empty($re['latest_point']['height'])) {
				$arr['data']['height'] = $re['latest_point']['height'];
			}else{
				$arr['data']['height'] = '';
			}
			if (!empty($re['latest_point']['speed'])) {
				$arr['data']['speed'] = $re['latest_point']['speed'];
			}else{
				$arr['data']['speed'] = '';
			}
			
			$arr['code'] = '200';
			$arr['msg'] = 'success';	
		}else{
			$arr['code'] = '500';
			$arr['msg'] = 'faild';
		}
		return $arr;
	}
	 /**
     * 模拟get请求
     * @param $url
     * @return mixed
     */
    public function get_curl_json($url){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
        $result = curl_exec($ch);
        if(curl_errno($ch)){
            print_r(curl_error($ch));
        }
        curl_close($ch);
        return json_decode($result,TRUE);
    }
	public function test()
	{
		$begintime=strtotime(date("Y-m-d H:i:s",mktime(0,0,0,date('m'),date('d'),date('Y'))));
		$endtime=strtotime(date("Y-m-d H:i:s",mktime(0,0,0,date('m'),date('d')+1,date('Y'))-1));
		// $re = Db :: table('order')
		// 	->leftJoin('order_extend','order.extendid','=','order_extend.id')
		// 	->leftJoin('order_status','order.num','=','order_status.order_number')
		// 	->where('order_extend.driver_id',1)
		// 	->whereBetween('order_status.update_time',[$begintime,$endtime])
		// 	->where('order.implementstatus','!=',1)
		// 	->distinct('order_status.order_number')
		// 	->count();
		$re = Db :: table('order')
			->leftJoin('order_extend','order.extendid','=','order_extend.id')
			->leftJoin('order_long','order.id','=','order_long.oid')
			->where('order_extend.driver_id',1)
			->where('order.orderstatus',4)
			->sum('endlong');
		dump($re);
		dump($begintime);
		dump($endtime);
	}
	//司机状态
	private function driverStatus($value)
	{
		switch ($value) {
			case 1:
				return '载客';
				break;
			case 2:
				return '接单';
				break;
			case 3:
				return '空驶';
				break;
			case 4:
				return '停运';
				break;
			case 5:
				return '休假';
				break;
			
			default:
				return '离职';
				break;
		}
	}
	//订单执行状态
	private function orderStatus($value)
	{
		switch ($value) {
			case 1:
				return '已下单';
				break;
			case 2:
				return '指派司机';
				break;
			case 3:
				return '司机接单';
				break;
			case 4:
				return '备车';
				break;
			case 5:
				return '前往预约地点';
				break;
			case 6:
				return '到达指定地点';
				break;
			case 7:
				return '开始服务';
				break;
			case 8:
				return '即将到达';
				break;
			
			default:
				return '结束服务';
				break;
		}
	}
	/**
	 * 计算价格
	 * $origins  string 起点纬经
	 * $destinations   string 终点纬经
	 * $types '即时用车'
	 * $carid 车系id
	 * $areaid 城市id
	 * $usetime 用车时间 2017-04-23 13:22
	 */
	private function price($origins, $destinations,$types, $usetime, $carid, $areaid)
	{
		
        $url = 'http://api.map.baidu.com/routematrix/v2/driving?output=json&origins=' . $origins . '&destinations=' . $destinations . '&ak=RGwhFRkSZfva32BN96csoObm4FIfiCAY';
        // return  $url;
        $result = $this->get_curl_json($url);
       // dump($result);
       	 $return = [];
        $time = round($result['result'][0]['duration']['value'] / 60);//时间
        $return['time'] = $time;
       // dump($time);
        $dis = round($result['result'][0]['distance']['value']/1000, 1);//距离
        $return['dis'] = $dis;
       // dump($dis);
       
        $price = 0;
        $typesId = Db :: table('server_item')->where('name',$types)->select('id')->first();
       // dump($typesId->id);
        $re = Db:: table('cost')
        		->where('sername',$typesId->id)->where('serid',$carid)->select('id','city')->get();
        $re = json_decode(json_encode($re),true);	
       // dump($re);
        $historyId = '';
        if(!empty($re)){
        	foreach ($re as $key => $value) {
        		$valueArr = explode(',',$value['city']);
        		if(in_array($areaid,$valueArr)){
        			 $historyId = $value['id'];
        			 continue;
        		}
        	}

        	if( $historyId == ''){
        		$return['price'] = 0;
	            $return['msg'] = '没有该服务';
	            return $return;
        	}
        }else{
        	$return['price'] = 0;
            $return['msg'] = '没有该服务';
            return $return;
        }
       	$algorithmid = Db :: table('history_algorithm')
       						->where('costid',$historyId)
       						->orderBy('id','desc')->select('algorithmid')->first();
       	$algorithmid = json_decode(json_encode($algorithmid),true);
       	if(empty($algorithmid)){
       		$return['price'] = 0;
            $return['msg'] = '没有该服务';
            return $return;
       	}
       	$algorithmidStr = $algorithmid['algorithmid'];
       	$re = Config::get('charge.'.$algorithmidStr);
        if (!empty($re)) {
            $difdis = $dis - $re['basis_km'];//实际距离与后台设置距离差
            //dump($difdis);
            if ($difdis > 0) {//实际距离大
                $difdis2 = $dis - $re['super_km_km'];//超过多少公里以后
               // dump($difdis2);
                if ($difdis2 < $re['super_km_shortage_km']) {//不做多少公里不计费
                    $price = $re['price'];
                    //dump($price);
                } else {//计算白天和夜间的超公里收费
                    $usetime1 = explode(' ', $usetime);
                    $usetime2 = strtotime($usetime);
                    $day_start_time = strtotime($usetime1[0] . $re['day_start_time']);
                    $day_end_time = strtotime($usetime1[0] . $re['day_end_time']);
                    $avgdis = $difdis2 / $re['super_km_per_km'];
                   // dump($avgdis);
                    if ($day_start_time < $usetime2 && $usetime2 < $day_end_time) {
                        $price = $re['price'] + $avgdis * $re['day_commission'];
                        //dump($price);
                    } else {
                        $price = $re['price'] + $avgdis * $re['night_commission'];
                    }
                }
            } else {//实际距离小
                $price = $re['price'];
            }
            $return['runprice'] = $price;
            $diftime = $time - $re['basis_time'];
            //dump($diftime);
            if ($diftime > 0) {//超时
                $diftime2 = $time - $re['starting_starting_time'];//起步后多少分钟内不收费
                if ($diftime2 < 0) {
                    $price = $price;
                } else {
                    $diftime3 = $diftime2 - $re['starting_shortage_time'];
                    if ($diftime3 < 0) {
                        $price = $price;
                    } else {
                        if($re['starting_exceed_time'] > 0){
                            $avgtime = $diftime3 / $re['starting_exceed_time'];
                        }else{
                            $avgtime = $diftime3;
                        }
                        
                        $price = $price + $avgtime * $re['starting_add_money'];
                    }
                }
            } else {//不超时
                $price = $price;
                //dump($price);
            }
            $return['oversprice'] = $price;
            $return['price'] = sprintf("%.2f",$price); 
            $return['msg'] = 'success';
        } else {
            $return['price'] = 0;
            $return['msg'] = '没有该服务';
        }
        return $return;
	}
	
}